"""
Case Type   : 系统函数
Case Name   : 执行 pg_terminate_backend 函数终止 UndoLauncher 线程
Create At   : 2024/7/25
Owner       : songjing20
Description :
    1.执行pg_terminate_backend 函数终止 UndoLauncher 线程
    2.查询数据库状态
Expect      :
    1.成功，UndoLauncher线程重新拉起
    2.数据库状态正常
History     : 
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant


class SystemFunction(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.commonsh = CommonSH('PrimaryDbUser')
        self.Constant = Constant()

    def test_sys_func(self):
        text = '-----step1:执行pg_terminate_backend 函数终止 UndoLauncher 线程;' \
               'expect:成功，UndoLauncher线程重新拉起-----'
        self.log.info(text)
        sql = f'''select pg_terminate_backend(
        (select tid from pg_catalog.gs_thread_memory_context 
        where thrdtype = 'UndoLauncher' limit 1));
        select pg_sleep(2);
        select * from pg_catalog.gs_thread_memory_context 
        where thrdtype = 'UndoLauncher' limit 1;'''
        res = self.commonsh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(' t\n(1 row)', res, f'执行失败:{text}')
        self.assertIn('UndoLauncher | ThreadTopMemoryContext', res,
                      f'执行失败:{text}')

        text = '-----step2:查询数据库状态;expect:数据库状态正常-----'
        self.log.info(text)
        res = self.commonsh.get_db_cluster_status('status')
        self.assertTrue(res, f'执行失败:{text}')

    def tearDown(self):
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
